<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  __DIR__ .'/../global_default_function.php';

function getCampaignFeed($header, $database, $user) {
	$doResponse = HttpPost('https://api.baidu.com/json/feed/v1/CampaignFeedService/getCampaignFeed', $header);
	if( !$doResponse ) {
		return;
	}
	$bodyArray = json_decode($doResponse, true);
	if( !is_array($bodyArray) ) {
		return;
	}
	if( !isset($bodyArray['header']) ) {
		return;
	}
	if( !isset($bodyArray['header']['desc']) ) {
		return;
	}
	if( $bodyArray['header']['desc'] != 'success' ) {
		return;
	}
	$campaignFeedIdArray = [];
	foreach($bodyArray['body']['data'] as $value) {
		array_push($campaignFeedIdArray, $value['campaignFeedId']);
		$value['budget'] = isset($value['budget']) ? $value['budget'] : 0;
		$res = $database->query("select id from cfg_campaign where `companyId` = '{$user['companyId']}' AND `userType` = 2 AND `campaignId` = '{$value['campaignFeedId']}' LIMIT 1");
		if( isset($res[0]['id']) ) {
			$database->query( "UPDATE cfg_campaign SET `bazaarId` = '{$user['bazaarId']}', `campaignName` = '{$value['campaignFeedName']}',
				`budget` = '{$value['budget']}',  `status` = '{$value['status']}', `datatime` = now() WHERE id = '{$res[0]['id']}'; ");
		} else {
			$database->query("INSERT INTO cfg_campaign ( `companyId`, `userType`, `bazaarId`, `userId`, `budget`, `campaignId`, `campaignName`, `status`, `datatime`) values (
			'{$user['companyId']}', 2, '{$user['bazaarId']}', '{$user['userid']}', '{$value['budget']}', '{$value['campaignFeedId']}', '{$value['campaignFeedName']}', '{$value['status']}', now()) " );
		}
	}
	switch (count($campaignFeedIdArray)) {
		case 0:
			$database->query(" DELETE FROM cfg_campaign WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userId` = {$user['userid']} " );
			$database->query(" DELETE FROM cfg_search WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userid` = {$user['userid']} AND `campaignid` > 0 " );
			break;
		case 1:
			$database->query(" DELETE FROM cfg_campaign WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userId` = {$user['userid']} AND `campaignId` <> {$campaignFeedIdArray[0]}" );
			$database->query(" DELETE FROM cfg_search WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userid` = {$user['userid']} AND `campaignid` > 0 AND `campaignid` <> {$campaignFeedIdArray[0]} " );
			break;
		default:
			$notinId = implode(',', $campaignFeedIdArray);
			$database->query(" DELETE FROM cfg_campaign WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userId` = {$user['userid']} AND `campaignId` NOT IN ($notinId) " );
			$database->query(" DELETE FROM cfg_search WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userid` = {$user['userid']} AND `campaignid` > 0 AND `campaignid` NOT IN ($notinId) " );
	}
}

run(function() use ($argv) {

	showMessage('读取信息流计划数据.' );

	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}

  $userList = $database->query('SELECT `id`, `companyId`, `rebate`, `bazaarId`, `userid`, `username`, `password`, `token` FROM cfg_expand where status = 1 and userType = 2');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}

	$userArray = array_chunk($userList, $config['curlnumber']);
  foreach ($userArray as $arrayList) {
		foreach ($arrayList as $user) {
			go(function() use ($config, $user)  {
				$database = new MySQL;
				$connect = $database->connect($config);
				if( $connect === false) {
					return;
				}
				showMessage($user['username'].'读取信息流数据.' );
				getCampaignFeed(json_encode([
					'header'=> [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'] ],
					'body'=> [
						"campaignFeedFields"=> [
								"campaignFeedId",
								"campaignFeedName",
								"budget",
								"status",
						]
					]
				]), $database, $user);
			});
		}
		Swoole\Coroutine::sleep(2);
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');